import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import Editor from '@/utils/Editor';
import {
  Row,
  Col,
  Button,
  Input,
  Modal,
  message,
  Icon,
  Tag,
  Pagination,
  Form,
  Drawer,
  Tabs,
  Collapse,
  Select,
  TreeSelect,
  Table, Spin,
  Switch,
  DatePicker,
  Radio,
} from 'antd';
import styles from './index.less';

const ExtendRt = React.lazy(() => import('../extendRt'));
const QuestionList = React.lazy(() => import('./question'));

const Search = Input.Search;
const id = 0;
const TabPane = Tabs.TabPane;
const { TextArea } = Input;
const { Panel } = Collapse;
const Option = Select.Option;
const users = ['afc163', 'benjycui', 'yiminghe', 'jljsj33', 'dqaria', 'RaoHai'];
const tags = ['1.0', '2.0', '3.0'];
const TreeNode = TreeSelect.TreeNode;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const confirm = Modal.confirm;
@connect(({ editQa, loading }) => ({
  editQa,
  loading: loading.effects['editQa/fetchApi'],
}))

class EditQa extends Component {
  constructor(props) {
    super(props);
    this.state={
      qaId:'',
      visible: false,
      modalTitle: '',
      isAddApi: false,
      isAddSlot: false,
      placeholder: "",
      list: [],
      type: null,
      page:1,
      limit:5,
      apiNames: '',
      keys: '',
      total: 0,
      apiObj:{},
      isShowApiTag:true,
      question: '',
      childrenDrawer: false,
      isShowMore: "none",
      suggestions: [],
      isShowSlot: false,
      questionIndex : null,
      overall:1,
      expandIconPosition: "right",
      answerArr: [
        {
          isDefault:true,
          content:"",
          answerType:"richText",
          slotValues:[],
          isEdit: false
        }
      ],
      answerArr_bak: [
        {
          isDefault:true,
          content:"",
          answerType:"richText",
          slotValues:[],
          isEdit: false
        }
      ],
      slotArr: [],
      slotDetailArr:[],
      treeData : [],
      categoryId: '',
      loading: false,
      classVisible: false,
      linkData:[],
      total: 0,
      classQuestion:'',
      classField:'q',
      searchClass:'',
      classPage:'1',
      classPageSize:'10',
      relateQAs:[],
      qaStatus: true,
      isForever:true,
      from:'',
      to:'',
      startTime:'',
      endTime:'',
      endOpen: false,
      qaActiveKeys:[],
      shared:'',
      synchronous:'',
      relateList:[],
      page: 1,
      questionIds:[],
      spinning: true,
      addLoading: true,
      isShowSimTitle: true,
      standardQus:'',
      questionArr:[],
      isFirstQus:false,
      questionsTotal:0,
      towQuestionArr:[],
      drawerLoading: true,
      towQuestionTotal: 0,
      searchVal: '',
      qusLimit:10,
      apiId:'',
      addQustions:[],
      editQuestions:[],
      delQuestions:[]
    };
    this.columns = [
      {
        title: '问题',
        key: 'question',
        dataIndex: 'question'
      },
      {
        title: '分类',
        key: 'category',
        dataIndex: 'category'
      },
      {
        title: '操作',
        render: (text, item) => {
          return  <div>
            {this.state.relateQAs.indexOf(item.sid) === -1?
              <Button htmlType='button' type="primary" size="small" onClick={(text) => { this.addLinkThis(item) }} icon='link'>关联 </Button>
              :
              <Button htmlType='button' size="small" icon='link'>已关联 </Button>
            }
          </div>
        }
      },
    ];
  }

  componentDidMount() {
    this.getCategoryListJson();
  }

  componentWillReceiveProps(nextProps, nextContext) {
    if(nextProps.qaId !== this.state.qaId && nextProps.qaId){
      this.setState({
        qaId: nextProps.qaId,
      },()=>{
        this.getAnswerDetailByQaid(nextProps.qaId);
        this.getQuestionsByQaid(nextProps.qaId);
        this.getStandardQuestionByQaId(nextProps.qaId)
      })
    }else{
      if(this.state.qaId === ''){
        this.setState({
          spinning: false,
          categoryId:nextProps.categoryIds=== ''?'':nextProps.categoryIds
        })
      }
    }
  }

  delSlot =(e,index,name,ids) => {
    e.preventDefault();
    const arr = this.state.answerArr_bak;
    const slotList = this.state.slotArr;
    const slotDetailArr = this.state.slotDetailArr;
    for(const i of arr){
      for(let j of i.slotValues){
        if(j.slotName === name){
          return message.error('该词槽被下面的答案引用，请删除/修改答案后尝试')
        }
      }
    }
    slotList.splice(index,1);
    let newSlotDetailArr = slotDetailArr.filter(item => item.id!== ids );
    this.setState({
      slotArr: slotList,
      slotDetailArr: newSlotDetailArr
    })
  };

  cleanApi=(e)=>{
    e.preventDefault();
    this.setState({
      apiObj: {},
      isShowApiTag: false,
      isAddApi: false,
      apiId:''
    });
  };

  addApi=()=>{

  };

  handleCancel = () => {
    this.setState({ visible: false});
  };

  showModal = (type) => {
    this.setState({
      visible: true,
      addLoading:true
    },()=>{
      switch (type) {
        case 'api':
          this.fetchApiListByRobotId();
          break;
        case 'slot':
          this.fetchSlotListByRobotId();
          break;
      }
    })
  };

  newCreate=()=>{
    const type = this.state.type
    switch (type) {
      case 'api':
        window.open('/basic/customApi');
        break;
      case 'slot':
        window.open('/basic/wordTroughManage');
        break;
    }

  };

  fetchApiListByRobotId=()=>{
    const { dispatch, currentUser } = this.props;
    const newPage = this.state.page;
    const newLimit = this.state.limit;
    const newApiNames = this.state.apiNames;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'editQa/fetchApi',
        payload: { robotId: currentUser.robotId, page: newPage, limit: newLimit, apiNames: newApiNames },
        callback: (res) => {
          this.setState({
            modalTitle:"添加API接口",
            placeholder: '请输入已有API接口',
            type: 'api',
            list: res.items,
            total: res.total,
            addLoading: false
          });
        }
      })
    });
  };

  fetchSlotListByRobotId=()=>{
    const { dispatch, currentUser } = this.props;
    const newPage = this.state.page;
    const newLimit = this.state.limit;
    const newKeys = this.state.keys;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'editQa/fetchSlot',
        payload: { robotId: currentUser.robotId, page: newPage, limit: newLimit, keys: newKeys },
        callback: (res) => {
          this.setState({
            modalTitle:"添加词槽",
            placeholder: '请输入已有词槽',
            type: 'slot',
            list: res.list,
            total: res.total,
            addLoading: false
          });
        }
      })
    });
  };

  selected=(item)=>{
    const type = this.state.type;
    switch (type) {
      case 'api':
        this.setState({
          isAddApi: true,
          apiObj: item,
          visible: false,
          isShowApiTag: true,
          apiId:item._id
        });
        break;
      case 'slot':
        const arr = this.state.slotArr;
        if(arr.length>=5){
          return message.error('词槽不可大于5个，请删除重试')
        }

        const result = arr.some(items => {
          return items.name == item.name
        });
        if(result){
          return message.error('该词槽已存在')
        }
        arr.push(item);
        console.log(item);
        this.setState({
          isAddSlot:true,
          visible: false,
          slotArr: arr
        });
        break;
    }
  };

  modalSearch=(val)=>{
    const type = this.state.type;
    switch (type) {
      case 'api':
        this.setState({
          apiNames:val
        },()=>{
          this.fetchApiListByRobotId();
        });
        break;
      case 'slot':
        this.setState({
          keys:val
        },()=>{
          this.fetchSlotListByRobotId();
        });
        break;
    }
  };



  // 翻页
  fanye(e,a) {
    const type = this.state.type;
    if(a){
      this.setState({
        classPage: e
      },()=>{
        return this.fetchLinkData()
      })
    }
    switch (type) {
      case 'api':
        this.setState({
          page: e,
        }, () => {
          this.fetchApiListByRobotId();
        });
        break;
      case 'slot':
        this.setState({
          page: e,
        }, () => {
          this.fetchSlotListByRobotId();
        });
        break;
    }

  }

  addQuestion=(val)=>{
    this.setState({
      question:val.target.value
    })
  };

  remove = (k) => {
    const { form } = this.props;
    const keys = form.getFieldValue('keys');
    if (keys.length === 1) {
      return;
    }

    form.setFieldsValue({
      keys: keys.filter(key => key !== k),
    });
  };

  add = (val) => {
    let arr = this.state.questionArr;
    let qus = this.state.standardQus;
    let addQus = this.state.addQuestions;
    if(arr.length ===0 && qus === ''){
      qus = val
    }else if(typeof val === 'object'){
      arr = arr.concat(val).reverse()
    }else{
      if(arr.indexOf(val) !== -1){
        return message.error('改问题已存在，请修改添加');
      }

      arr.unshift(val)
    }

    this.setState({
      question: '',
      questionArr: arr,
      standardQus: qus,
      page:1
    })
  };

  showChildrenDrawer = () => {
    this.setState({
      childrenDrawer: true,
      isShowSimTitle: false
    });
    this.getQuestionsByQaid(this.state.qaId,true);
    this.getStandardQuestionByQaId(this.state.qaId);
  };

  onChildrenDrawerClose = () => {
    this.setState({
      childrenDrawer: false,
      isShowSimTitle: true
    });
  };

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { keys, names } = values;
      }
    });
  };

  fixQuestion=(e,val,index)=>{
    const arr = this.state.questionArr;
    arr[index]= e.target.value;
    this.setState({
      questionArr : arr
    })
  };

  showSlot=(e)=>{
    this.setState({
      isShowSlot:true
    })
  };

  hideSlot=(e)=>{
    this.setState({
      question: e.target.value,
      isShowSlot: false
    })
  };

  showQuestionSlot=(e,index)=>{
    this.setState({
      questionIndex: index
    })
  };

  hideQuestionSlot=(e,index)=>{
    this.setState({
      questionIndex: null
    })
  };

  setAsk =(val,index)=>{
    const { form } = this.props;
    const keys = form.getFieldValue('keys');
    const keys0 = keys[0];
    keys[0] = val;
    keys[index] = keys0;
    form.setFieldsValue({
      keys
    });
  };

  enterHistory=()=>{
    window.open('/knowledge/amendantRecord')
  };

  callback(key,index) {
    const arr = this.state.answerArr;
    arr[index].answerType = key;
    this.setState({
      answerArr: arr
    })
  };


  onEditQa=(index,type)=>{
    const arr = this.state.answerArr;
    if(index !== -1 && type !== 'save' ){
      arr[index].isEdit = !arr[index].isEdit;
      this.setState({
        answerArr: arr
      });
    }
    switch (type) {
      case 'save':
        this.setDefaultAnswer(index);
        break;
      case 'del':
        this.delDefaultAnswer(index,'del');
        break;
      case 'add':
        this.addAnswer();
      case 'edit':
        this.editAnswer();
        break;
      case 'cancel':
        this.delDefaultAnswer(index,'cancel');
        break;
    }
  };

  addSlotToQuestion=(val,index)=>{
    if(index !== ''){
      const { form } = this.props;
      const keys = form.getFieldValue('keys');
      const value =  `${keys[index]}<${val}>`;
      keys[index] = value;
      form.setFieldsValue({
        keys
      });
    }else{
      const value = `${this.state.question}<${val}>`;
      this.setState({
        question: value
      })
    }
  };

  setDefaultAnswer=(index)=>{
    const answer = this.state.answerArr;
    const answer_bak = this.state.answerArr_bak;
    const type = answer[index].answerType;
    const slots_bak = answer_bak[index].slotValues;
    const isDefault = answer[index].isDefault;
    answer[index].slotValues = slots_bak;
    const slots = answer[index].slotValues;
    if(slots.length === 0 && !isDefault){
      return message.error('词槽答案词槽不允许为空，请添加词槽再保存')
    }
    if(slots.length===1 && !isDefault){
      for(const i of slots) {
        if (i.values.length == 0) {
          return message.error('词槽答案词槽不允许为空，请添加词槽再保存')
        }
      }
    }
    let content = '';
    const con = `content${index}`;
    switch (type) {
      case 'richText':
        content = this.refs[con].getUeditorContent();
        break;
      case 'text':
        content = this.state.textValue;
        break;
    }
    answer[index].content = content;
    answer[index].isEdit = !answer[index].isEdit;
    const qaActiveKeys = this.state.qaActiveKeys;
    qaActiveKeys.push(answer.length.toString());
    console.log(answer)
    this.setState({
      answerArr: answer,
      qaActiveKeys
    });
  };

  delDefaultAnswer=(index,type)=>{
    const arr_bak = this.state.answerArr_bak;
    const arr = this.state.answerArr;
    const isDefault = arr_bak[index].isDefault;
    const isEdit = arr_bak[index].isEdit;
    switch (type) {
      case 'del':
        if(!isDefault){
          if(arr[index].slotValues.length === 0){
            arr_bak.splice(index,1);
            arr.splice(index,1);
          }else{
            arr_bak.splice(index,1);
            arr.splice(index,1);
          }
          this.setState({
            answerArr_bak: arr_bak,
            answer: arr
          });
        }
        break;
      case 'cancel':
        console.log('取消保存');
        if(!isDefault){
          if(!isEdit){
            arr_bak.splice(index,1);
            arr.splice(index,1);
          }
        }
        break;
    }

  };

  getTextValue=(e)=>{
    const value = e.target.value;
    this.setState({
      textValue : value
    })
  };

  addAnswer=()=>{
    const answers = this.state.answerArr;
    const answer_bak = this.state.answerArr_bak;
    let arr = [];
    let arr_bak = [];
    arr = arr.concat(answers);
    arr_bak = arr_bak.concat(answer_bak);
    arr.unshift({
      isDefault:false,
      content:"",
      answerType:"richText",
      slotValues:[],
      isEdit: false
    });
    arr_bak.unshift({
      isDefault:false,
      content:"",
      answerType:"richText",
      slotValues:[],
      isEdit: false
    });
    const slotList = this.state.slotArr;
    for(const i of slotList){
      this.fetchSlotDetailBySlotId(i._id,i.name)
    }
    this.setState({
      answerArr: arr,
      answerArr_bak: arr_bak
    })
  };

  editAnswer=()=>{
    const slotList = this.state.slotArr;
    console.log(slotList,'-----------------slotList')
    for(const i of slotList){
      this.fetchSlotDetailBySlotId(i._id,i.name)
    }
  };

  fetchSlotDetailBySlotId=(id,name)=>{
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'editQa/getDictItemFromSlotId',
        payload: { slotId:id },
        callback: (res) => {
          console.log(res,'根据词槽查询词槽详情')
          res[0].name = name;
          res[0].id = id;
          const arr = this.state.slotDetailArr;
          console.log(arr)
          let newArr = [];
          const result = arr.some(items => {
            return items.name == res[0].name
          });

          if(!result){
            newArr = newArr.concat(arr);
            newArr = newArr.concat(res);
            this.setState({
              slotDetailArr: newArr
            })
          }
        }
      })
    });
  };


  addSlotForSelect=(value,index,slotIndex,_id,newName)=>{
    const arr = this.state.answerArr_bak;
    let oldSlotArr = arr[index].slotValues;
    let newArr = oldSlotArr.filter(item=>item.slotName === newName);
    if(newArr.length>0){
      oldSlotArr[slotIndex].values = value
    }else{
      oldSlotArr.push({
        id:_id,
        values: value,
        slotName: newName
      });
    }
    this.setState({
      answerArr_bak: arr
    })
  };

  editSlotByUnSelect=(value,index)=>{
    const arr = this.state.answerArr_bak;
    const slots =  arr[index].slotValues;
    slots.forEach( ( item ) => {
      item.values.forEach((s,j)=>{
        if(s === value){
          item.values.splice(j,1)
        }
      })
    });
    this.setState({
      answerArr_bak: arr
    })
  };

  addLinkQa=()=>{
    this.setState({
      classVisible: true
    });
    this.fetchLinkData();
  };

  getCategoryListJson=()=>{
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'editQa/categoryListJson',
        payload: { },
        callback: (res) => {
          const arr = [];
          arr.push(res[0]);
          this.setState({
            treeData:arr
          })
        }
      })
    });
  };

  renderTreeNodes=(data)=> {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.text} key={item.data.path} value={item.data.path}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={item.text} key={item.data.path} value={item.data.path} />;
    });
  }

  onTreeChange=(value,label, extra)=>{
    this.setState({ categoryId:value})
  };

  fetchLinkData=( )=>{
    this.setState({
      loading: true
    },()=>{
      const { dispatch, currentUser } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'editQa/linkBoxJson',
          payload: { robotId:currentUser.robotId, question:this.state.classQuestion,field:this.state.classField, query:this.state.searchClass, page:this.state.classPage,limit:this.state.classPageSize },
          callback: (res) => {
            const  arr= res.qaList;
            this.setState({
              total:res.total,
              linkData: arr,
              loading: false,
            })
          }
        })
      });
    });
  };

  classHandleCancel=()=>{
    this.setState({
      classVisible: false
    })
  };

  addLinkThis=(item)=>{
    let arr = [];
    let relateArr = [];
    arr = arr.concat(this.state.relateQAs);
    arr.unshift(item.sid);
    relateArr = relateArr.concat(this.state.relateList);
    relateArr.unshift(item);
    this.setState({
      relateQAs:arr,
      relateList:relateArr
    },()=>{
    });
  };

  onShowSizeChange=(current, pageSize)=>{
    this.setState({
      classPage:current,
      classPageSize: pageSize
    },()=>{
      this.fetchLinkData()
    })
  };

  classSelectChange=(e)=>{
    this.setState({
      classField:e
    },()=>{
      this.fetchLinkData()
    })
  };

  searchClass=(e)=>{
    this.setState({
      searchClass:e.target.value
    },()=>{
      this.fetchLinkData()
    })
  };

  onDelRelateQa=(index,qa)=>{
    const arr = this.state.relateList;
    let {relateQAs} = this.state;
    console.log(qa,this.state.relateQAs);
    for(let i =0;i<relateQAs.length;i++){
      if(relateQAs[i] === qa.sid){
        relateQAs.splice(i,1)
      }
    }
    arr.splice(index,1);
    this.setState({
      relateList: arr,
      relateQAs
    })
  };

  onSetRelateQa=(index)=>{
    const arr = this.state.relateList;
    if(index!==0){
      arr[index] = arr.splice(index-1, 1, arr[index])[0];
    }else{
      arr.push(arr.shift());
    }

    this.setState({
      relateList: arr
    })
  };

  onChangeQaStatus=(checked)=>{
    this.setState({
      qaStatus: checked
    })
  };

  onChangeQaIsForever=(e)=>{
    this.setState({
      isForever: e.target.value
    })
  };

  onStartChange = (value,dateString) => {
    this.onDateChange('startTime', value,dateString);
  };

  onEndChange = (value,dateString) => {
    this.onDateChange('endTime', value,dateString);
  };

  handleStartOpenChange = (open) => {
    if (!open) {
      this.setState({ endOpen: true });
    }
  };

  handleEndOpenChange = (open) => {
    this.setState({ endOpen: open });
  };

  onDateChange = (field, value,dateString) => {
    this.setState({
      [field]: value
    });
    switch (field) {
      case 'startTime':
        this.setState({
          from:dateString
        });
        break;
      case 'endTime':
        this.setState({
          to:dateString
        });
        break;
    }
  };

  saveQa(categoryId){
    const questionList = this.state.questionArr;
    const { dispatch } = this.props;
    const arr = this.state.relateList;
    const newArr = [];
    for(const i of arr){
      if(i.sid){
        newArr.push(i.sid)
      }else{
        newArr.push(i.id)
      }
    }
    questionList.unshift(this.state.standardQus);
    let slotIdArr = [];
    for(let i of this.state.slotArr){
      slotIdArr.push(i._id)
    }
    let obj ={ };
    if(this.state.qaId){
      obj ={
        unresolvedId:'',
        unknownId:'',
        apiId:this.state.apiId,
        slots:slotIdArr,
        relateQAs:newArr,
        categoryId: this.state.categoryId =="" ?'/': this.state.categoryId,
        answers:this.state.answerArr,
        qaId:this.state.qaId,
        questions:questionList,
        isSharedQA:false,
        isSynchronous:false,
        disabled:!this.state.qaStatus,
        isForever:this.state.isForever,
        from:this.state.from,
        to:this.state.to
      };
    }else{
      obj ={
        unresolvedId:'',
        unknownId:'',
        apiId:this.state.apiId,
        slots:slotIdArr,
        relateQAs:newArr,
        categoryId:this.state.categoryId =="" ?'/': this.state.categoryId,
        answers:this.state.answerArr,
        questions:questionList,
        qaId:this.state.qaId,
        isSharedQA:false,
        isSynchronous:false,
        disabled:!this.state.qaStatus,
        isForever:this.state.isForever,
        from:this.state.from,
        to:this.state.to
      };
    }

    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'editQa/saveKp',
        payload: obj,
        callback: (res) => {
          if(res.msg){
            message.info(res.msg);
          }else{
            message.info('保存成功')
          }
          this.setState({
            relateQAs: []
          },()=>{
            this.props.onClose();
          })
        }
      })
    });
  };

  cancelSaveQa=()=>{
    this.setState({
      relateQAs: []
    },()=>{
      this.props.onClose();
    })
  };

  getAnswerDetailByQaid=(qaId)=> {
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'editQa/getDetailByQaid',
        payload: {id:qaId},
        callback: (res) => {
          console.log(res.categoryId,'------------------当前分类id');
          this.setState({
            categoryId:res.categoryId,
            qaStatus: res.disabled,
            apiId: !res.apiId===true?'':res.apiId,
            apiObj: !res.api===true?'':res.api,
            isForever: res.enableTime.isForever,
            from: !res.enableTime.from ===true?'':res.enableTime.from,
            to: !res.enableTime.to ===true?'':res.enableTime.to,
            slotArr: !res.slotList ===true?[]:res.slotList,
            isAddSlot: !res.slotList ===true?false:res.slotList.length>0,
            isAddApi: !res.apiId ===true?false:true ,
            relateList: !res.relateList===true?[]:res.relateList,
            shared: !res.shared ===true?false:res.shared,
            synchronous: !res.synchronous ===true?false:res.synchronous,
          },()=>{
            console.log(this.state.categoryId,'state');
            this.getJsonAnswerByQaId(this.state.qaId)
          })
        }
      })
    })
  };

  getQuestionsByQaid=(qaId,isTowDrawer)=>{
    const { dispatch } = this.props;
    let limitNum=9999999999999;
    if(isTowDrawer){
      limitNum = this.state.qusLimit;
    }
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'editQa/getQuestionsByQaId',
        payload: {id:qaId,limit:limitNum,page:this.state.page,search:this.state.searchVal },
        callback: (res) => {
          const arr = [];
          for(const i of res.list){
            arr.push(i.question);
          }
          if(isTowDrawer){
            this.setState({
              towQuestionArr: arr,
              towQuestionTotal:res.total,
              drawerLoading: false
            })
          }else{
            this.setState({
              questionArr: arr,
              questionsTotal: res.total
            })
          }
        }
      })
    })
  };

  getStandardQuestionByQaId=(qaId)=>{
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'editQa/getStandardQuestionByQaId',
        payload: {id:qaId},
        callback: (res) => {
          this.setState({
            standardQus: res.question
          })
        }
      })
    })
  };

  getJsonAnswerByQaId=(id)=>{
    const { dispatch,form } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'editQa/getJsonAnswerByQaId',
        payload: {qaId:id,isShared: this.state.shared,isSynchronous: this.state.synchronous},
        callback: (res) => {
          for(const i of res){
            i.isEdit= true
          }
          this.setState({
            spinning: false,
            answerArr: res,
            answerArr_bak: res
          })
        }
      })
    })
  };

  removeQuestion=(e,index)=>{
    const arr = this.state.questionArr;
    this.setState({
      questionArr: arr.filter(key => key !== e),
    })
  };

  setStandard=(e)=>{
    const standard = this.state.standardQus;
    let arr = this.state.questionArr;
    arr = arr.filter(key => key !== e);
    arr.unshift(standard);
    this.setState({
      standardQus: e,
      questionArr: arr
    })
  };

  modifiedStandard=(val)=>{
    this.setState({
      standardQus: val
    })
  };

  addSlotToNomalQuestion=(name)=>{
    const value = `${this.state.standardQus}<${name}>`;
    this.setState({
      standardQus: value
    })
  };

  addSlotToSmQuestion=(name,index)=>{
    const {questionArr} = this.state;
    const value =  `${questionArr[index]}<${name}>`;
    questionArr[index]= value;
    this.setState({
      questionArr
    })
  };

  getQusBySearch=(e)=>{
    const val = e.target.value;
    this.setState({
      drawerLoading: true,
      searchVal: val
    },()=>{
      this.getQuestionsByQaid(this.state.qaId,true)
    })
  };

  showTotal=(total)=>{
    return `共${total} 条`;
  };

  pageChange=(num)=>{
    this.setState({
      page: num,
      drawerLoading: false
    })
  };

  pageSizeChange=(current,size)=>{
    this.setState({
      qusLimit: size,
      drawerLoading: false
    })
  };


  pagination=(pageNo, pageSize, array)=> {
    var offset = (pageNo - 1) * pageSize;
    return (offset + pageSize >= array.length) ? array.slice(offset, array.length) : array.slice(offset, offset + pageSize);
  };

  render() {
    let questionTotal = this.state.questionArr.length;
    let questionTow = this.pagination(this.state.page,this.state.qusLimit,this.state.questionArr);
    const genExtra = (index,isDefault) => (
      <span>
        <Icon
          type="edit"
          style={{marginLeft:10}}
          onClick={(event) => {
            event.stopPropagation();
            this.onEditQa(index,'edit');
          }}
        />
        { !isDefault ?<Icon
          type="close"
          style={{marginLeft:10}}
          onClick={(event) => {
            event.stopPropagation();
            this.onEditQa(index,'del');
          }}
        />: ''
        }
      </span>
    );

    const slotList = this.state.slotArr;
    const {qaStatus} = this.state;
    return (
      <Suspense fallback={<PageLoading />}>
        <Spin tip="Loading..." spinning={this.state.spinning}>
          <Row
            gutter={16}
          >
            <div style={{overflow:"hidden"}}>
              <div style={{float:"right"}}>
                <span style={{marginLeft: 10,cursor:'pointer'}} onClick={()=>this.enterHistory()}>  <Icon type="clock-circle" theme="twoTone" /> 历史</span>
                <Button style={{marginLeft: 10}} onClick={()=>this.showModal('api')}>添加Api接口</Button>
                <Button style={{marginLeft: 10}} onClick={()=>this.showModal('slot')}>添加词槽</Button>
              </div>
            </div>
            <div>
              {this.state.isAddSlot?
                <div>
                  <div className={styles.label}>词槽</div>
                  <div className={styles.labelWarp}>
                    {
                      slotList.map((slot,index)=>{
                        return (
                          <Tag closable className={styles.slotTag} onClose={(e)=>this.delSlot(e,index,slot.name,slot._id)}>&lt;{slot.name}&gt;-{slot.key}</Tag>
                        )
                      })
                    }
                  </div>
                </div>:''}
              {
                this.state.isAddApi?<div>
                  <div className={styles.label}>API接口</div>
                  <div className={styles.labelWarp}>
                    <span>触发知识点时调用接口</span>
                    {this.state.isShowApiTag?<span><Tag closable className={styles.apiTag} onClose={this.cleanApi}>{this.state.apiObj.name}</Tag><Icon style={{marginLeft:10}} onClick={()=>this.showModal('api')} type="edit" /></span>:''}
                  </div>
                </div>:''
              }
              <div>
                <div className={styles.label}>问题</div>
                <div className={styles.labelWarp}>
                  <QuestionList
                    slots={slotList}
                    isTowDrawer={false}
                    qaId={this.state.qaId}
                    add={(value)=>this.add(value)}
                    total={this.state.questionsTotal}
                    questions={ this.state.qaId ?this.state.questionArr.slice(0,6):this.state.questionArr}
                    standardQus={this.state.standardQus}
                    seeMore={()=>this.showChildrenDrawer()}
                    isShowMore={this.state.questionArr.length>6}
                    remove={(e,index)=>this.removeQuestion(e,index)}
                    modifiQus={(e,k,index)=>this.fixQuestion(e,k,index)}
                    modifiedStandard={(val)=>this.modifiedStandard(val)}
                    getTopQus={(e)=>this.getStandardQuestionByQaId(e)}
                    setStandardQus={(e,index)=>this.setStandard(e,index)}
                    getQusList={(id)=>this.getQuestionsByQaid(id,false)}
                    addSlotToNomalQuestion={(name)=>this.addSlotToNomalQuestion(name)}
                    addSlotToSmQuestion={(name,index)=>this.addSlotToSmQuestion(name,index)}
                  />
                </div>
              </div>
              <div>
                <div>
                  <Row>
                    <Col span={4}>
                      <div className={styles.label}>答案</div>
                    </Col>
                    <Col span={2} offset={16}>
                      <div>{this.state.slotArr.length>0 ? <Button htmlType='button' style={{marginLeft: 10}} type="primary" size='small' icon="plus" onClick={()=>this.onEditQa(-1,'add')}>添加答案</Button> :''} </div>
                    </Col>
                  </Row>
                </div>

                <div className={styles.labelWarp}>
                  {
                    this.state.answerArr.map((answer,index)=>{
                      return (
                        <div key={index}>
                          {
                            !answer.isEdit ?
                              <div className={styles.answerWarp}>
                                {
                                  answer.isDefault?
                                    <Row>
                                      <Col span={5}>
                                        { index === 0? " " :' 其它情况默认答案'}
                                      </Col>
                                      <Col span={5} offset={14}>
                                        <Button htmlType='button' style={{marginLeft: 10}} onClick={()=>this.onEditQa(index,'cancel')}>取消</Button>
                                        <Button htmlType='button' style={{marginLeft: 10}} onClick={()=>this.onEditQa(index,'save')}>保存</Button>
                                      </Col>
                                    </Row>
                                    :
                                    <Row>
                                      <Col span={15}>
                                        {
                                          this.state.slotDetailArr.map((slotDetailItem,slotIndex)=>{
                                            return (
                                              <Row style={{marginTop: 10}}>
                                                {slotDetailItem.isEnum ?
                                                  <div>
                                                    <Col span={4} style={{ textAlign: "right" }}>
                                                      {slotDetailItem.name}:
                                                    </Col>
                                                    <Col span={18} offset={1}>
                                                      {
                                                        answer.slotValues.length > 0 ?
                                                          <Select
                                                            mode="multiple"
                                                            style={{ width: '100%' }}
                                                            placeholder="请选择词槽"
                                                            onBlur={(value) => this.addSlotForSelect(value,index, slotIndex, slotDetailItem.id, slotDetailItem.name)}
                                                            onDeselect={(value)=>this.editSlotByUnSelect(value,index, slotIndex, slotDetailItem.id, slotDetailItem.name)}
                                                            defaultValue={answer.slotValues[slotIndex].values}
                                                          >
                                                            {
                                                              slotDetailItem.items.map(function(item, itemIndex) {
                                                                return (<Option key={item.word}>{item.word}</Option>)
                                                              })
                                                            }
                                                          </Select>
                                                          : <Select
                                                            mode="multiple"
                                                            style={{ width: '100%' }}
                                                            placeholder="请选择词槽"
                                                            onDeselect={(value)=>this.editSlotByUnSelect(value,index, slotIndex, slotDetailItem.id, slotDetailItem.name)}
                                                            onBlur={(value) => this.addSlotForSelect(value,index, slotIndex, slotDetailItem.id, slotDetailItem.name)}
                                                          >
                                                            {
                                                              slotDetailItem.items.map(function(item, itemIndex) {
                                                                return (<Option key={item.word}>{item.word}</Option>)
                                                              })
                                                            }
                                                          </Select>
                                                      }
                                                    </Col>
                                                  </div>
                                                  :
                                                  <div>
                                                    <Col span={4} style={{ textAlign: "right" }}>
                                                      {slotDetailItem.name}:
                                                    </Col>
                                                    <Col span={18} offset={1}>
                                                      <span style={{color:'lightgrey'}}> 词槽值不可枚举，不支持设置条件</span>
                                                    </Col>
                                                  </div>
                                                }
                                              </Row>
                                            )
                                          })
                                        }
                                      </Col>
                                      <Col span={5} offset={4}>
                                        <Button htmlType='button' style={{marginLeft: 10}} onClick={()=>this.onEditQa(index,'cancel')}>取消</Button>
                                        <Button htmlType='button' style={{marginLeft: 10}} onClick={()=>this.onEditQa(index,'save')}>保存</Button>
                                      </Col>
                                    </Row>
                                }
                                <Row>
                                  <Tabs type="card" defaultActiveKey={answer.answerType} onChange={(key)=>this.callback(key,index)} style={{marginTop: 10}}>
                                    <TabPane tab="富文本" key="richText">
                                      <div style={{width: 712}}>
                                        <Editor content={answer.content} name={`content${index}`} id={`content${index}`} ref={`content${index}`} />
                                      </div>
                                    </TabPane>
                                    <TabPane tab="文本" key="text">
                                      <TextArea rows={6} onChange={(e)=>this.getTextValue(e,index)} />
                                    </TabPane>
                                  </Tabs>
                                </Row>
                              </div> :
                              <div>
                                <Collapse defaultActiveKey={this.state.qaActiveKeys} expandIconPosition={this.state.expandIconPosition} style={{marginTop: 10}}>
                                  {
                                    !answer.isDefault ?
                                      <Panel
                                        header={answer.slotValues.map((slotValueItem,slotValueIndex)=>{
                                          return (
                                            <span key={slotValueIndex}>
                                            &lt;{slotValueItem.slotName}&gt;=<Tag color="#108ee9">{slotValueItem.values.map((tag,tagIndex)=>{return(<span key={tagIndex} style={{marginLeft:5,marginRight:5}}>{tag}</span>)})}</Tag>
                                            </span>
                                          )
                                        })}
                                        key={index}
                                        extra={genExtra(index,answer.isDefault)}
                                      >
                                        <div className={styles.previewAnswer} dangerouslySetInnerHTML={{ __html: answer.content }} />
                                      </Panel>
                                      :
                                      <Panel header="普通答案" key={index} extra={genExtra(index,answer.isDefault)}>
                                        <div dangerouslySetInnerHTML={{ __html: answer.content }} />
                                      </Panel>
                                  }
                                </Collapse>
                              </div>
                          }
                        </div>
                      )
                    })
                  }
                </div>
              </div>
              <div>
                <Row>
                  <Col span={4}>
                    <div className={styles.label}>关联问题</div>
                  </Col>
                  <Col span={2} offset={16}>
                    <div><Button htmlType='button' style={{marginLeft: 10}} type="primary" size='small' onClick={()=>this.addLinkQa()}>添加关联知识点</Button></div>
                  </Col>
                </Row>
                <div className={styles.labelWarp}>
                  {
                    this.state.relateList.map((qa,qaIndex)=>{
                      return (
                        <div style={{marginTop:10}}>
                          <Row>
                            <Col span={22}>
                              <Input value={qa.question} key={qaIndex} disabled className={styles.relateQa} />
                            </Col>
                            <Col span={2}>
                              <Icon
                                className="dynamic-delete-button"
                                type="close-circle"
                                onClick={()=>this.onDelRelateQa(qaIndex,qa)}
                                style={{fontSize:20,marginLeft:10,cursor:"pointer",marginTop:5}}
                              />
                              {qaIndex>0?<Icon type="arrow-up" onClick={()=>this.onSetRelateQa(qaIndex)} style={{fontSize:20,marginLeft:10,cursor:"pointer",marginTop:5}}  />:''}
                            </Col>
                          </Row>
                        </div>
                      )
                    })
                  }
                </div>
              </div>
              <div>
                <Row>
                  <Col span={4}>
                    <div className={styles.label}>知识点分类</div>
                  </Col>
                </Row>
                <div className={styles.labelWarp}>
                  <Row>
                    <Col span={3}>
                      选择分类
                    </Col>
                    <Col span={8}>
                      <TreeSelect
                        showSearch
                        allowClear
                        treeDefaultExpandAll
                        style={{ width: 300 }}
                        treeNodeFilterProp='title'
                        value={this.state.categoryId =="" ?'/': this.state.categoryId}
                        placeholder="点击选择知识点分类"
                        treeDefaultExpandedKeys={['root']}
                        showCheckedStrategy={TreeSelect.SHOW_ALL}
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        onChange={(value,label, extra)=>this.onTreeChange(value,label, extra)}
                      >
                        {this.renderTreeNodes(this.state.treeData)}
                      </TreeSelect>
                    </Col>
                  </Row>

                </div>
              </div>
              <div>
                <Row>
                  <Col span={4}>
                    <div className={styles.label}>生效时间</div>
                  </Col>
                </Row>
                <div className={styles.labelWarp}>
                  <Row>
                    <Col span={3}>
                      知识点状态
                    </Col>
                    <Col span={8}>
                      <Switch checkedChildren="启用" unCheckedChildren="禁用" defaultChecked={qaStatus} onChange={this.onChangeQaStatus}  />
                    </Col>
                  </Row>
                  <Row style={{marginTop: 10}}>
                    <Col span={3}>
                      知识点有效期
                    </Col>
                    <Col span={8}>
                      <RadioGroup onChange={this.onChangeQaIsForever} value={this.state.isForever}>
                        <Radio value>永久有效</Radio>
                        <Radio value={false}>自定义有效期</Radio>
                      </RadioGroup>
                    </Col>
                  </Row>
                  <Row style={{marginTop: 10}}>
                    <Col span={16} offset={3}>
                      { !this.state.isForever? <div>
                        <DatePicker
                          format="YYYY-MM-DD "
                          value={this.state.startTime}
                          placeholder="开始日期"
                          onChange={this.onStartChange}
                          onOpenChange={this.handleStartOpenChange}
                        />
                        <span style={{margin:"0 10px"}}>至</span>
                        <DatePicker
                          format="YYYY-MM-DD "
                          value={this.state.endTime}
                          placeholder="结束日期"
                          onChange={this.onEndChange}
                          open={this.state.endOpen}
                          onOpenChange={this.handleEndOpenChange}
                        />
                      </div>:''}
                    </Col>
                  </Row>
                </div>
              </div>
              <div>
                <Row style={{marginTop: 30}}>
                  <Col span={8} offset={3}>
                    <Button htmlType='button' onClick={this.cancelSaveQa} style={{marginRight:10}}>取消</Button>
                    <Button type="primary" htmlType='button' onClick={()=>this.saveQa()}>保存</Button>
                  </Col>
                </Row>
              </div>
            </div>
          </Row>
        </Spin>
        <Modal
          visible={this.state.visible}
          title={this.state.modalTitle}
          onCancel={this.handleCancel}
          footer={[<Pagination defaultCurrent={1} defaultPageSize='5' key='123' onChange={e => this.fanye(e)} total={this.state.total} size="small" /> ]}
          width={350}
          key='1'
          centered
        >
          <div>
            <Search
              placeholder={this.state.placeholder}
              onSearch={value => this.modalSearch(value)}
              style={{ width: 200 }}
            />
            <Button htmlType='button' style={{marginLeft: 10}} onClick={()=>this.newCreate()}>新建</Button>
          </div>
          <div className={styles.modalBody}>
            <Spin spinning={this.state.addLoading}>
              {
                this.state.list.map((api,index)=>{
                  return (
                    <div className={styles.modalItem} key={index}>
                      <Button htmlType='button' size='small' type="primary" onClick={()=>this.selected(api)}>选择</Button>
                      {this.state.type === 'api'? <span style={{marginLeft: 10}}>{api.name}</span>:<span style={{marginLeft: 10}}>&lt;{api.key}&gt; ({api.name})</span>}
                    </div>
                  )
                })
              }
            </Spin>
          </div>
        </Modal>
        <Drawer
          title={
            <span  onClick={this.onChildrenDrawerClose} style={{cursor:'pointer'}}>
                <Icon type="arrow-left" style={{ marginRight: 20 }} />
                返回
              </span>
          }
          width={700}
          closable={false}
          destroyOnClose
          onClose={this.onChildrenDrawerClose}
          visible={this.state.childrenDrawer}
        >
          <Spin spinning={this.state.drawerLoading}>
            <QuestionList
              slots={slotList}
              isShowMore={false}
              isTowDrawer={true}
              qaId={this.state.qaId}
              questions={questionTow}
              add={(value)=>this.add(value)}
              search={(e)=>this.getQusBySearch(e)}
              standardQus={this.state.standardQus}
              seeMore={()=>this.showChildrenDrawer()}
              remove={(e,index)=>this.removeQuestion(e,index)}
              getTopQus={(e)=>this.getStandardQuestionByQaId(e)}
              modifiQus={(e,k,index)=>this.fixQuestion(e,k,index)}
              modifiedStandard={(val)=>this.modifiedStandard(val)}
              setStandardQus={(e,index)=>this.setStandard(e,index)}
              getQusList={(id)=>this.getQuestionsByQaid(id,true)}
              addSlotToNomalQuestion={(name)=>this.addSlotToNomalQuestion(name)}
              addSlotToSmQuestion={(name,index)=>this.addSlotToSmQuestion(name,index)}
            />
          </Spin>
          <div style={{overflow:'hidden',marginTop:'-30px'}}>
            <Pagination
              size="small"
              showSizeChanger
              showQuickJumper
              total={questionTotal}
              style={{float:'right'}}
              current = {this.state.page}
              showTotal={()=>this.showTotal(questionTotal)}
              onChange={(pageNumber)=>this.pageChange(pageNumber)}
              onShowSizeChange={(current,size)=>this.pageSizeChange(current,size)}
            />
          </div>
        </Drawer>
        <Modal
          visible={this.state.classVisible}
          title='选择关联问题'
          onCancel={this.classHandleCancel}
          footer={[]}
          width={750}
          key='2'
          centered
        >
          <Form layout="inline" style={{ paddingBottom: 20 }}>
            <FormItem>
              <Select
                style={{ width: 160 }}
                defaultValue={this.state.classField}
                onChange={this.classSelectChange}
              >
                <Option value='q'>搜索问题</Option>
                <Option value='a'>搜索答案</Option>
              </Select>
            </FormItem>
            <FormItem>
              <Input
                style={{ width: 320 }}
                placeholder="请输入内容"
                suffix={
                  <Icon type="search" />
                }
                onPressEnter={this.searchClass}
                allowClear
              />
            </FormItem>
          </Form>
          <Spin spinning={this.state.loading}>
            <Table
              style={{ height:500,overflow:"auto"}}
              size='small'
              columns={this.columns}
              dataSource={this.state.linkData}// 数据
              rowKey='sid'
              pagination={{  // 分页
                total: this.state.total, // 数据总数量
                pageSize: this.state.pageSize,  // 显示几条一页
                showSizeChanger: true,  // 是否显示可以设置几条一页的选项
                onChange: (e)=>this.fanye(e,'class'),
                onShowSizeChange: this.onShowSizeChange,
                showQuickJumper:true
              }}
            />
          </Spin>
        </Modal>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser
}))(Form.create()(EditQa));
